package cn.yu.meeting.common.interceptors;

import cn.yu.meeting.common.utils.JwtUtil;
import cn.yu.meeting.common.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * 拦截器用于拦截接口处理逻辑
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token");

        try {
            if (!StringUtils.hasLength(token)) {
                throw new RuntimeException("token 为空");
            }
            //存储一下token到redis
            ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
            String token2 = stringStringValueOperations.get(token);
            if (token2 == null) {
                //token 失效了
                throw new RuntimeException("token 失效了");
            }
            Map<String, Object> claims = JwtUtil.parseToken(token);
            ThreadLocalUtil.set(claims);
            //接口方形
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(401);
            //拦截接口
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        //请求完成后,清空临时存储的信息
        ThreadLocalUtil.remove();
    }
}
